﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MySqlCode
{
    public partial class Add : Form
    {
        /// <summary>
        /// 1-增加    2-修改
        /// </summary>
        public int Mode { get; set; }
        public string GUID { get; set; }

        public Add()
        {
            InitializeComponent();
        }

        private static Add _add;
        public static Add GetInstance()
        {
            if (_add == null) _add = new Add();
            return _add;
        }

        public void SetModel(Model.DataInfo model)
        {
            this.GUID = model.GUID;
            this.txtHost.Text = model.Host;
            this.txtName.Text = model.Name;
            this.txtPort.Text = model.Port;
            this.txtUser.Text = model.User;
            this.txtPwd.Text = model.Pwd;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (Mode == 1)
            {
                var model = new Model.DataInfo()
                {
                    GUID = Guid.NewGuid().ToString("N"),
                    Host = txtHost.Text,
                    Name = txtName.Text,
                    Port = txtPort.Text,
                    User = txtUser.Text,
                    Pwd = txtPwd.Text
                };
                App.Insert(model);
                Connector.GetInstance().ShowData();
                this.Close();
            }
            else
            {
                var model = new Model.DataInfo()
                {
                    GUID = GUID,
                    Host = txtHost.Text,
                    Name = txtName.Text,
                    Port = txtPort.Text,
                    User = txtUser.Text,
                    Pwd = txtPwd.Text
                };
                App.Update(model);
                Connector.GetInstance().ShowData();
                this.Close();
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            var model = new Model.DataInfo()
            {
                Host = txtHost.Text,
                Name = txtName.Text,
                Port = txtPort.Text,
                User = txtUser.Text,
                Pwd = txtPwd.Text
            };

            var db = Mode==2? new Handler.MySQLHelper(App.Database):new Handler.MySQLHelper(model);
            var isSucc = db.TestOpen();
            if (isSucc) MessageBox.Show("连接成功", "提示");
            else MessageBox.Show("连接失败", "警告");
        }
    }
}
